#include <Arduino.h>
#include <WebServer.h>
#include <WiFi.h>

void wifiConnect(void);
void serverStart(void);
void sendDataHandler(void);

String data = "{'light':0,'temp':0,'hum':0}"; // sever返回数据

WebServer server(5000);

void wifiConnect(void) // 连接wifi并打印ESP32 IP
{
    const char *ssid = "wifi_SSID";
    const char *password = "wifi_PASSWORD";
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to WiFi");
    Serial.println(WiFi.localIP());
}

void serverStart(void) // 启动http服务
{
    server.on("/data", sendDataHandler); // URL:http://192.168.1.4:5000/data
    server.begin();
    Serial.println("Web server started");
}

void sendDataHandler() // 发送请求数据
{
    data = "{'light':1,'temp':30,'hum':60}";
    server.send(200, "text/plain", data);
}

void setup()
{
    wifiConnect();
    serverStart();
}

void loop()
{
    server.handleClient();
}
